<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <div class="aftersale-member-form">
          <div class="form-header">
            <div class="header-icon">
              <Icon icon="ant-design:user-add-outlined" class="member-icon" />
            </div>
            <div class="header-content">
              <h3 class="form-title">添加售后成员</h3>
              <p class="form-subtitle">配置售后服务团队成员信息</p>
            </div>
          </div>
          
          <a-form class="member-form" v-bind="formItemLayout" ref="formRef" name="AfterSaleMembersForm">
            <a-row :gutter="24">
						<!-- 隐藏售后表id字段 -->
						<!-- <a-col :span="24">
							<a-form-item label="售后表id" v-bind="validateInfos.afterSaleId" id="AfterSaleMembers-afterSaleId" name="afterSaleId">
								<a-input v-model:value="formData.afterSaleId" placeholder="请输入售后表id"  allow-clear ></a-input>
							</a-form-item>
						</a-col> -->
						<a-col :span="12">
							<a-form-item label="部门" v-bind="validateInfos.departId" id="AfterSaleMembers-departId" name="departId">
								<a-select 
									v-model:value="formData.departId" 
									placeholder="请选择所属部门" 
									size="large"
									:allow-clear="!disabled"
									:show-arrow="!disabled"
									@change="handleDepartmentChange"
									:loading="departLoading"
									class="form-select"
								>
									<template #suffixIcon>
										<Icon icon="ant-design:apartment-outlined" />
									</template>
									<a-select-option 
										v-for="dept in departList" 
										:key="dept.id" 
										:value="dept.id"
									>
										<div class="select-option">
											<Icon icon="ant-design:bank-outlined" class="option-icon" />
											<span>{{ dept.departName }}</span>
										</div>
									</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="成员" v-bind="validateInfos.sysUserId" id="AfterSaleMembers-sysUserId" name="sysUserId">
								<a-select 
									v-model:value="formData.sysUserId" 
									placeholder="请选择团队成员" 
									size="large"
									:allow-clear="!disabled"
									:show-arrow="!disabled"
									@change="handleUserChange"
									:loading="userLoading"
									:disabled="!formData.departId"
									class="form-select"
								>
									<template #suffixIcon>
										<Icon icon="ant-design:user-outlined" />
									</template>
									<a-select-option 
										v-for="user in userList" 
										:key="user.id" 
										:value="user.id"
									>
										<div class="select-option">
											<a-avatar :size="20" style="background-color: #1890ff; margin-right: 8px;">
												{{ user.realName ? user.realName[0] : 'U' }}
											</a-avatar>
											<span>{{ user.realName }}</span>
										</div>
									</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="成员姓名" v-bind="validateInfos.name" id="AfterSaleMembers-name" name="name">
								<a-input 
									v-model:value="formData.name" 
									placeholder="请输入成员姓名"
									size="large"
									class="form-input"
									allow-clear
								>
									<template #prefix>
										<Icon icon="ant-design:user-outlined" />
									</template>
								</a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="成员角色" v-bind="validateInfos.role" id="AfterSaleMembers-role" name="role">
								<a-select 
									v-model:value="formData.role" 
									placeholder="请选择成员角色" 
									size="large"
									:allow-clear="!disabled" 
									:show-arrow="!disabled"
									class="form-select"
								>
									<template #suffixIcon>
										<Icon icon="ant-design:team-outlined" />
									</template>
									<a-select-option value="项目经理">
										<div class="role-option">
											<a-tag color="red">项目经理</a-tag>
											<span>负责项目整体管理</span>
										</div>
									</a-select-option>
									<a-select-option value="技术负责人">
										<div class="role-option">
											<a-tag color="blue">技术负责人</a-tag>
											<span>负责技术方案设计</span>
										</div>
									</a-select-option>
									<a-select-option value="开发人员">
										<div class="role-option">
											<a-tag color="green">开发人员</a-tag>
											<span>负责功能开发实现</span>
										</div>
									</a-select-option>
									<a-select-option value="测试人员">
										<div class="role-option">
											<a-tag color="orange">测试人员</a-tag>
											<span>负责质量测试保证</span>
										</div>
									</a-select-option>
									<a-select-option value="运维人员">
										<div class="role-option">
											<a-tag color="purple">运维人员</a-tag>
											<span>负责系统运维保障</span>
										</div>
									</a-select-option>
									<a-select-option value="商务人员">
										<div class="role-option">
											<a-tag color="cyan">商务人员</a-tag>
											<span>负责商务沟通协调</span>
										</div>
									</a-select-option>
									<a-select-option value="客服人员">
										<div class="role-option">
											<a-tag color="geekblue">客服人员</a-tag>
											<span>负责客户服务支持</span>
										</div>
									</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="任务状态" v-bind="validateInfos.completion" id="AfterSaleMembers-completion" name="completion">
								<a-select 
									v-model:value="formData.completion" 
									placeholder="请选择任务状态" 
									size="large"
									:allow-clear="!disabled" 
									:show-arrow="!disabled"
									class="form-select"
								>
									<template #suffixIcon>
										<Icon icon="ant-design:clock-circle-outlined" />
									</template>
									<a-select-option value="未开始">
										<div class="status-option">
											<a-tag color="default">未开始</a-tag>
											<span>任务尚未开始</span>
										</div>
									</a-select-option>
									<a-select-option value="进行中">
										<div class="status-option">
											<a-tag color="processing">进行中</a-tag>
											<span>任务正在执行</span>
										</div>
									</a-select-option>
									<a-select-option value="已完成">
										<div class="status-option">
											<a-tag color="success">已完成</a-tag>
											<span>任务已经完成</span>
										</div>
									</a-select-option>
									<a-select-option value="已暂停">
										<div class="status-option">
											<a-tag color="warning">已暂停</a-tag>
											<span>任务暂时停止</span>
										</div>
									</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="任务内容" v-bind="validateInfos.assignment" id="AfterSaleMembers-assignment" name="assignment">
								<a-textarea 
									v-model:value="formData.assignment" 
									placeholder="请详细描述该成员的具体任务内容和职责范围..."
									:rows="4"
									show-count
									:maxlength="500"
									class="form-textarea"
									allow-clear
								/>
							</a-form-item>
						</a-col>
						<!-- 隐藏逻辑删除字段 -->
						<!-- <a-col :span="24">
							<a-form-item label="逻辑删除" v-bind="validateInfos.isDeleted" id="AfterSaleMembers-isDeleted" name="isDeleted">
								<a-input-number v-model:value="formData.isDeleted" placeholder="请输入逻辑删除" style="width: 100%" />
							</a-form-item>
						</a-col> -->
            </a-row>
          </a-form>
        </div>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, onMounted, inject, defineProps, unref } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getValueType } from '/@/utils';
  import { afterSaleMembersSaveOrUpdate } from '../AfterSales.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { useUserStore } from '/@/store/modules/user';
  import { message } from 'ant-design-vue';

  //接收主表id
  const mainId = inject('mainId');
  const userStore = useUserStore();
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
        afterSaleId: '',   
        departId: '',
        sysUserId: '',   
        name: '',   
        role: '',   
        assignment: '',   
        completion: '',   
        isDeleted: undefined,
  });

  // 部门和用户相关
  const departList = ref([]);
  const userList = ref([]);
  const departLoading = ref(false);
  const userLoading = ref(false);

  // API接口配置
  const api = {
    getAllDepart: `/jeecg-boot/sys/sysDepart/getAllDepart`,
    getUserByDepartId: `/jeecg-boot/sys/sysDepart/getUsersByDepartId`,
  };

  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = {
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
  const props = defineProps({
    disabled: { type: Boolean, default: false },
  });
  const formItemLayout = {
    labelCol: { xs: { span: 24 }, sm: { span: 5 } },
    wrapperCol: { xs: { span: 24 }, sm: { span: 16 } },
  };

  // 获取所有部门信息
  const fetchAllDepartments = async () => {
    try {
      departLoading.value = true;
      const response = await defHttp.get({ 
        url: api.getAllDepart,
      });
      console.log("获取所有部门响应： ", response);
      if (response.success) {
        departList.value = response.result || [];
      } else {
        message.error(response.message || '获取部门信息失败');
        departList.value = [];
      }
    } catch (error) {
      console.error('获取部门信息失败:', error);
      message.error('获取部门信息失败');
      departList.value = [];
    } finally {
      departLoading.value = false;
    }
  };

  // 根据部门ID获取用户列表
  const fetchUsersByDepartId = async (departId) => {
    try {
      userLoading.value = true;
      const response = await defHttp.get({ 
        url: api.getUserByDepartId,
        params: { id: departId },
      });

      if (response.success) {
        userList.value = response.result || [];
      } else {
        message.error(response.message || '获取部门人员失败');
        userList.value = [];
      }
    } catch (error) {
      console.error('获取部门人员失败:', error);
      message.error('获取部门人员失败');
      userList.value = [];
    } finally {
      userLoading.value = false;
    }
  };

  // 处理部门选择变化
  const handleDepartmentChange = (value) => {
    if (value) {
      const selectedDepart = departList.value.find(item => item.id === value);
      if (selectedDepart) {
        fetchUsersByDepartId(selectedDepart.id);
        formData.departId = selectedDepart.id;
      }
    } else {
      userList.value = [];
      formData.sysUserId = undefined;
      formData.name = undefined;
    }
  };

  // 处理用户选择变化
  const handleUserChange = (value) => {
    if (value) {
      const selectedUser = userList.value.find(item => item.id === value);
      if (selectedUser) {
        formData.sysUserId = selectedUser.id;
        formData.name = selectedUser.realName;
      }
    }
  };
  
  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      // 处理数据库字段名映射
      if (record.after_sale_id) {
        tmpData.afterSaleId = record.after_sale_id;
      }
      if (record.sys_user_id) {
        tmpData.sysUserId = record.sys_user_id;
      }
      if (record.depart_id) {
        tmpData.departId = record.depart_id;
      }
      if (record.name) {
        tmpData.name = record.name;
      }
      if (record.role) {
        tmpData.role = record.role;
      }
      if (record.assignment) {
        tmpData.assignment = record.assignment;
      }
      if (record.completion) {
        tmpData.completion = record.completion;
      }
      if (record.is_deleted !== undefined) {
        tmpData.isDeleted = record.is_deleted;
      }

      //赋值
      Object.assign(formData, tmpData);
      
      // 如果是编辑模式，需要加载部门和用户信息
      if (record.id) {
        fetchAllDepartments();
        if (formData.departId) {
          fetchUsersByDepartId(formData.departId);
        }
      } else {
        // 新增模式，只加载部门信息
        fetchAllDepartments();
      }
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch (e: any) {
      if (e && e.errorFields) {
        const firstField = e.errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(e);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await afterSaleMembersSaveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .aftersale-member-form {
    .form-header {
      display: flex;
      align-items: center;
      gap: 16px;
      margin-bottom: 32px;
      padding: 20px 24px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border-radius: 12px;
      box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);

      .header-icon {
        width: 56px;
        height: 56px;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.2);
        display: flex;
        align-items: center;
        justify-content: center;
        backdrop-filter: blur(10px);
        border: 2px solid rgba(255, 255, 255, 0.3);

        .member-icon {
          font-size: 24px;
          color: white;
        }
      }

      .header-content {
        .form-title {
          margin: 0;
          font-size: 20px;
          font-weight: 600;
          color: white;
        }

        .form-subtitle {
          margin: 4px 0 0 0;
          color: rgba(255, 255, 255, 0.8);
          font-size: 14px;
        }
      }
    }

    .member-form {
      .ant-form-item {
        margin-bottom: 24px;

        .ant-form-item-label {
          > label {
            font-weight: 600;
            color: #262626;
            font-size: 15px;
          }
        }

        .form-input {
          border-radius: 8px;
          border: 2px solid #e8e8e8;
          transition: all 0.3s;
          font-size: 14px;
          
          &:hover {
            border-color: #40a9ff;
          }
          
          &:focus, &.ant-input-focused {
            border-color: #1890ff;
            box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.1);
          }

          .anticon {
            color: #8c8c8c;
          }
        }

        .form-select {
          border-radius: 8px;
          
          :deep(.ant-select-selector) {
            border: 2px solid #e8e8e8;
            border-radius: 8px;
            transition: all 0.3s;
          }

          &:hover :deep(.ant-select-selector) {
            border-color: #40a9ff;
          }

          &.ant-select-focused :deep(.ant-select-selector) {
            border-color: #1890ff;
            box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.1);
          }

          :deep(.ant-select-arrow) {
            color: #8c8c8c;
          }
        }

        .form-textarea {
          border-radius: 8px;
          border: 2px solid #e8e8e8;
          transition: all 0.3s;
          font-size: 14px;
          resize: vertical;
          
          &:hover {
            border-color: #40a9ff;
          }
          
          &:focus, &.ant-input-focused {
            border-color: #1890ff;
            box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.1);
          }
        }

        .select-option {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 4px 0;

          .option-icon {
            color: #8c8c8c;
          }
        }

        .role-option,
        .status-option {
          display: flex;
          align-items: center;
          gap: 12px;
          padding: 4px 0;

          span {
            font-size: 12px;
            color: #666;
          }
        }
      }
    }
  }

  // 重写原有样式
  .antd-modal-form {
    padding: 0;
  }

  // 下拉框选项样式优化
  :deep(.ant-select-dropdown) {
    border-radius: 8px;
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);

    .ant-select-item {
      border-radius: 6px;
      margin: 2px 4px;
      
      &:hover {
        background: #f0f7ff;
      }

      &.ant-select-item-option-selected {
        background: #e6f7ff;
        font-weight: 500;
      }
    }
  }
</style>
